import iotaAxios from '@cmiot/iota-axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'
import { isEqual } from 'lodash'

const showMessage = (
  message,
  type = 'error',
  showClose = true,
  duration = 3000
) => {
  Message({ type, showClose, duration, message })
}
const whiteUrlList = ['/open/queryProvincesList']
const service = iotaAxios.create({
  axiosConfig: {
    baseURL: process.env.VUE_APP_BASE_URL_API,
    timeout: 35000,
  },
  isCancelSameRequest: true,
  isSameRequest: (currentConfig, compareConfig) => {
    return (
      `${currentConfig.url}_${currentConfig.method.toUpperCase()}` ===
        `${compareConfig.url}_${compareConfig.method.toUpperCase()}` &&
      isEqual(currentConfig.data, compareConfig.data) &&
      !whiteUrlList.includes(currentConfig.url)
    )
  },
  requestInterceptors: [
    {
      onFulfilled: (config) => {
        const hasToken = localStorage.getItem('LG_TK')
        if (hasToken) config.headers['token'] = hasToken
        return config
      },
      onRejected: (error) => {
        return Promise.reject(error)
      },
      key: 'requestKey',
    },
  ],
  responseInterceptors: [
    {
      onFulfilled: (response) => {
        const res = response.data
        const headers = response.headers
        const message = res.message || '服务器错误'
        const code = res.code // 不返回code默认是1
        if (response.status === 200) {
          // hasLogoutStatus = code === -101 || code === -102
          if (response.data instanceof Blob) {
            if (response.data.type === 'application/json') {
              let fileReader = new FileReader()
              return new Promise((resolve, reject) => {
                fileReader.onload = () => {
                  const errRes = JSON.parse(fileReader.result)
                  // showMessage(errRes.message)
                  switch (errRes.code) {
                    case 1:
                      showMessage(errRes.message, 'success')
                      break
                    default:
                      showMessage(errRes.message)
                  }
                  return reject(errRes.message)
                }
                fileReader.readAsText(res)
              })
            } else {
              if (
                response.headers &&
                response.headers['rsa-public-key'] &&
                response.headers['rsa-check-key']
              ) {
                return Promise.resolve({
                  data: res,
                  headers: headers,
                })
              } else {
                console.log(5555555)
                return Promise.resolve(res)
              }
            }
          }
          switch (code) {
            case 1:
              return Promise.resolve(res.data)
            case -101:
              service.removeAllRequest()
              showMessage(message)
              store.dispatch('fedLogOut').then(() => {
                window.self === window.parent
                  ? router.push('/login')
                  : window.parent.postMessage({ token: 'invalid' }, '*')
              })
              return Promise.reject(message)
            case -102:
              service.removeAllRequest()
              showMessage(message)
              store.dispatch('fedLogOut').then(() => {
                window.self === window.parent
                  ? router.push('/login')
                  : window.parent.postMessage({ token: 'invalid' }, '*')
              })
              return Promise.reject(message)
            case 40030: //代理商下有套餐电站
              return Promise.reject(res)
            default:
              showMessage(message)
              return Promise.reject(res)
          }
        } else {
          showMessage(message)
          return Promise.reject(res)
        }
      },
      onRejected: (error) => {
        // hasLogoutStatus = false
        if (error && error.response) {
          const err = error.response.data
          const code = err.code
          const message = err.message
          switch (code) {
            case -101:
              service.removeAllRequest()
              showMessage(message)
              store.dispatch('fedLogOut').then(() => {
                window.self === window.parent
                  ? router.push('/login')
                  : window.parent.postMessage({ token: 'invalid' }, '*')
              })
              return Promise.reject(message)
            case -102:
              service.removeAllRequest()
              showMessage(message)
              store.dispatch('fedLogOut').then(() => {
                window.self === window.parent
                  ? router.push('/login')
                  : window.parent.postMessage({ token: 'invalid' }, '*')
              })
              return Promise.reject(message)
            default:
              showMessage(message)
              return Promise.reject(message)
          }
        }
        return Promise.reject(error)
      },
      key: 'responseKey',
    },
  ],
})

export default service
